import { getAppNav } from '@/App'
import LocalStorageKey from '@/constant/LocalStorageKey'
import SessionStorageKey from '@/constant/SessionStorageKey'
import { useAppSelector } from '@/store'
import { removeAppLoading } from '@/util/CommonUtil'
import {
  IllustrationNotFound,
  IllustrationNotFoundDark,
} from '@douyinfe/semi-illustrations'
import { Button, Empty } from '@douyinfe/semi-ui'
import { useEffect } from 'react'
import { Navigate } from 'react-router-dom'

export default function Exception404() {
  const loadMenuFlag = useAppSelector((state) => state.common.loadMenuFlag) // 是否获取过菜单
  const jwt = localStorage.getItem(LocalStorageKey.JWT)

  const toAdminFlag = !loadMenuFlag && jwt

  useEffect(() => {
    if (!toAdminFlag) {
      removeAppLoading() // 移除 appLoading
    }
    document.title = '404' // 修改标题，备注：这里需要单独设置
  }, [])

  if (toAdminFlag) {
    sessionStorage.setItem(
      SessionStorageKey.ADMIN_REDIRECT_PATH,
      window.location.pathname
    ) // 记录当前地址，admin路由加载完成之后，直接跳转这个地址
    return <Navigate to={'/admin'} />
  }

  return (
    <Empty
      className="vwh100 flex-center"
      image={<IllustrationNotFound />}
      darkModeImage={<IllustrationNotFoundDark />}
      title="页面不存在 _φ_(．．)"
    >
      <div className="flex-center" title="返回">
        <Button block size="large" type="primary" onClick={() => backClick()}>
          返回
        </Button>
      </div>
    </Empty>
  )
}

// 点击返回按钮
function backClick() {
  if (window.history.length === 1 || window.history.length === 2) {
    getAppNav()('/') // 防止直接打开 /404，然后返回时没有可以返回的 路由，所以就直接返回 /
  } else {
    getAppNav()(-1)
  }
}
